<?php
    /*
    #####################################
    #  ShopOS: Shopping Cart Software.
    #  http://shopos3.com
    #####################################
    */

    //совместимость со старой версией
    $db = new db();
  /*  class data
    {
        public function __call($name, $params)
        {      
           if ( method_exists('db', $name) == true)
           {
              return call_user_func_array( "db::$name", $params);    
           }
        }
    }
    */
    class db {
        static $link;
        static $server = DB_SERVER;
        static $username = DB_SERVER_USERNAME;
        static $password = DB_SERVER_PASSWORD;
        static $database = DB_DATABASE;
        static $use_pconnect = USE_PCONNECT;
        static $cache;
        /* constant */
        static $DB_CACHE = false;
        static $STORE_DB_TRANSACTIONS = false;
        static $DISPLAY_DB_QUERY = false;
        static $SEARCH_ENGINE_FRIENDLY_URLS = false;
        static $AJAX_CART = false;
        //stats
        static $query_counts;
        static $db_query = array();

        public static function connect() 
        {
            if (self::$use_pconnect == 'true') 
            {
                self::$link = mysql_pconnect(db::$server, db::$username, db::$password);
            } 
            else 
            {
                self::$link = @mysql_connect(db::$server, db::$username, db::$password, self::$link); 
            }

            if (self::$link)
            {
                @mysql_select_db(db::$database);
                @mysql_query("SET NAMES 'utf8' COLLATE 'utf8_general_ci'");
            }

            if (!self::$link) 
            {
                db::error("connect", mysql_errno(), mysql_error());
            }

            return true;
        }

        public static function query($query) 
        {
            self::$query_counts++; 

            if ( defined("STORE_DB_TRANSACTIONS") && STORE_DB_TRANSACTIONS == 'true') 
            {
                error_log('QUERY ' . $query . "\n", 3, STORE_PAGE_PARSE_TIME_LOG);
            }

            $mtime = microtime(); 
            $mtime = explode(" ",$mtime); 
            $mtime = $mtime[1] + $mtime[0]; 
            $tstart = $mtime; 

            $result = mysql_query($query) or db::error($query, mysql_errno(), mysql_error());

            $mtime = microtime(); 
            $mtime = explode(" ",$mtime); 
            $mtime = $mtime[1] + $mtime[0]; 
            $tend = $mtime; 
            $tpassed = ($tend - $tstart); 

            $tpassed = number_format($tpassed, 5);

            if ( defined("STORE_DB_TRANSACTIONS") && STORE_DB_TRANSACTIONS == 'true') 
            {
                $result_error = mysql_error();
                error_log('RESULT ' . $result . ' ' . $result_error . "\n", 3, STORE_PAGE_PARSE_TIME_LOG);
            }

            if (!$result) 
            {
                db::$error($query, mysql_errno(), mysql_error());
            }

            if (defined('DISPLAY_DB_QUERY') && DISPLAY_DB_QUERY == 'true')
            {

                $db_text = $query;
                $db_text = str_replace("\r\n", "", $db_text); 
                $db_text = str_replace("\n","",$db_text);
                $db_text = strtolower($db_text);
                $db_text = trim($db_text);
                $db_text = preg_replace("|[\s]+|s", " ", $db_text);

                if ( isset( self::$db_query[$db_text] ) )
                {
                    self::$db_query[$db_text]['num']++;
                    self::$db_query[$db_text]['time'] = $tpassed;
                }	
                else
                {
                    self::$db_query[$db_text]['num'] = 1;
                    self::$db_query[$db_text]['time'] = $tpassed;
                }		
            }
            
            return $result;
        }

        public static function fetch_array(&$db_query, $cq=false)
        {
            if (self::$DB_CACHE=='true' && $cq) 
            {
                if (!count($db_query)) return false;
                if (is_array($db_query)) 
                {
                    $curr = current($db_query);
                    next($db_query);
                }
                return $curr;
            } 
            else 
            {
                if (is_array($db_query)) 
                {
                    $curr = current($db_query);
                    next($db_query);
                    return $curr;
                }
                return @mysql_fetch_array($db_query, MYSQL_ASSOC);
            }
        }

        public static function error($query, $errno, $error) 
        {
            $log = date("d/m/Y H:m:s",time()) . ' | ' . $errno . ' - ' . $error . ' | ' . $query . ' | ' . $_SERVER["REQUEST_URI"] . "\n";

            echo '<textarea class="round" style="color:red;width:100%; height:100px;">'.$log.'</textarea>';
            die();
        }

        public static function cache_query($query) 
        {
            if (self::$DB_CACHE == 'true') 
            {
                $result = db::cached($query);
            } 
            else 
            {
                $result = db::query($query);
            }
            return $result;
        }


        public static function cached($query)
        {
            self::$query_counts++; 

            if ( isset(self::$db_query[$query]) )
            {
                self::$db_query[$query]['num']++;
                self::$db_query[$query]['time'] = $tpassed;
            }	
            else
            {
                self::$db_query[$query]['num'] = 1;
                self::$db_query[$query]['time'] = $tpassed;
            }	
            // get HASH ID for filename
            $id=md5($query);

            // cache File Name
            $file=SQL_CACHEDIR.$id.'.db';

            // file life time
            $expire = DB_CACHE_EXPIRE; // 24 hours

            if (defined('STORE_DB_TRANSACTIONS') && STORE_DB_TRANSACTIONS == 'true') 
            {
                error_log('QUERY ' . $query . "\n", 3, STORE_PAGE_PARSE_TIME_LOG);
            }

            if (file_exists($file) && filemtime($file) > (time() - $expire)) 
            {
                $result = unserialize(implode('',file($file)));

            } 
            else 
            {

                if (file_exists($file)) @unlink($file);

                // get result from DB and create new file
                $result = db::query($query, self::$link) or db::$error($query, mysql_errno(), mysql_error());

                if (STORE_DB_TRANSACTIONS == 'true') {
                    $result_error = mysql_error();
                    error_log('RESULT ' . $result . ' ' . $result_error . "\n", 3, STORE_PAGE_PARSE_TIME_LOG);
                }

                // fetch data into array
                while ($record = db::$fetch_array($result))
                    $records[]=$record;


                // safe result into file.

                $stream = serialize($records);
                $fp = fopen($file,"w");
                fwrite($fp, $stream);
                db::$cache[$id] = $stream;
                fclose($fp);
                $result = unserialize(implode('',file($file)));

            }

            return $result;
        }

        public static function input($string) 
        {
            if (function_exists('mysql_real_escape_string')) 
            {
                return mysql_real_escape_string($string);
            } 
            elseif (function_exists('mysql_escape_string')) 
            {
                return mysql_escape_string($string);
            }

            return addslashes($string);
        }

        public static function prepare_input($string) 
        {
            if (is_string($string)) 
            {
                return trim(stripslashes($string));
            } 
            elseif (is_array($string)) 
            {
                reset($string);
                while (list($key, $value) = each($string)) 
                {
                    $string[$key] = db::$prepare_input($value);
                }
                return $string;
            } 
            else 
            {
                return $string;
            }
        }

        public static function data_seek($db_query, $row_number,$cq=false) 
        {
            if (DB_CACHE=='true' && $cq) 
            {
                if (!count($db_query)) return;
                return $db_query[$row_number];
            } 
            else 
            {
                if (!is_array($db_query)) return mysql_data_seek($db_query, $row_number);
            }
        }

        public static function categoriesstatus_for_product($product_id) 
        {
            $categorie_query = "SELECT categories_id FROM ".TABLE_PRODUCTS_TO_CATEGORIES."WHERE products_id='".$product_id."'";
            $categorie_query = db::$db_query($categorie_query);

            while ($categorie_data = db::$fetch_array($categorie_query, true)) 
            {
                if (os_check_categories_status($categorie_data['categories_id']) >= 1) 
                {
                    return 1;
                } 
                else 
                {
                    return 0;
                }
                echo $categorie_data['categories_id'];
            }
        } 

        public static function close() 
        {
            return mysql_close(self::$link);
        }

        public static function insert_id() 
        {
            return mysql_insert_id();
        }

        public static function output($string) 
        {
            return htmlspecialchars($string);
        }

        public static function select_db($database) 
        {
            return mysql_select_db($database);
        }

        public static function fetch_fields($db_query) 
        {
            return mysql_fetch_field($db_query);
        }

        public static function num_rows($db_query,$cq=false) 
        {
            if (DB_CACHE=='true' && $cq) 
            {
                if (!count($db_query)) return false;
                return count($db_query);
            } 
            else 
            {
                if (!is_array($db_query)) return mysql_num_rows($db_query);
            }
        }

        //получает количество рядов, задействованных в предыдущей MySQL-операции.
        public static function affected_rows()
        {
            return mysql_affected_rows ();
        }

        /* public static function insert_array($table, $data)
        {
        $insert_count = 40;
        $c = 0;
        print_r($data);
        if (count($data) > 0)
        {
        $cols_array = array();

        foreach ($data as $value)
        {
        foreach ($value as $name=>$val)
        {
        $_val[] = $val;
        $cols_array[$name]=1;
        }

        $_val_insert = '('.implode(',', $_val ).')';
        $_val_array[] = $_val_insert;
        $_val_insert = '';
        $_val = '';

        $c ++;

        if ($c >= $insert_count)
        {
        $_val_array = implode(',', $_val_array );

        //print_r($_val_array);

        print_r($cols_array);
        //$_val_array = '';
        die();
        //db::query('insert into '.$table.' values');
        }
        }

        }


        }
        */
        public static function perform($table, $data, $action = 'insert', $parameters = '', $link = 'db_link') 
        {
            reset($data);

            if ($action == 'insert') 
            {
                $query = 'insert into ' . $table . ' (';
                while (list($columns, ) = each($data)) 
                {
                    $query .= $columns . ', ';
                }

                $query = substr($query, 0, -2) . ') values (';
                reset($data);

                while (list(, $value) = each($data)) 
                {
                    $value = (is_Float($value) & PHP4_3_10) ? sprintf("%.F",$value) : (string)($value);
                    switch ($value) 
                    {
                        case 'now()':
                            $query .= 'now(), ';
                            break;
                        case 'null':
                            $query .= 'null, ';
                            break;
                        default:
                            $query .= '\'' . db::input($value) . '\', ';
                            break;
                    }
                }
                $query = substr($query, 0, -2) . ')';
            } 
            elseif ($action == 'update') 
            {
                $query = 'update ' . $table . ' set ';
                while (list($columns, $value) = each($data)) 
                {
                    $value = (is_Float($value) & PHP4_3_10) ? sprintf("%.F",$value) : (string)($value);
                    switch ($value) 
                    {
                        case 'now()':
                            $query .= $columns . ' = now(), ';
                            break;
                        case 'null':
                            $query .= $columns .= ' = null, ';
                            break;
                        default:
                            $query .= $columns . ' = \'' . db::input($value) . '\', ';
                            break;
                    }
                }
                $query = substr($query, 0, -2) . ' where ' . $parameters;
            }

            return db::query($query, $link);
        }

        function test_connection($database) 
        {
            global $db_error;

            $db_error = false;

            if (!$db_error) 
            {
                if ( !@self::select_db($database) ) 
                {
                    $db_error = mysql_error();
                } 
                else 
                {
                    if (!@self::query("select count(*) from " . TABLE_CONFIGURATION . "")) 
                    {
                        $db_error = mysql_error();
                    }
                }
            }

            if ($db_error) 
            {
                return false;
            } 
            else 
            {
                return true;
            }
        }

    }
    
    include_once(_FUNC.'db.php');
?>
